//
// Created by benxb on 2021/11/12.
//

#include <sstream>
#include "catelog/column.h"
#include <cstring>

namespace benxdb {

std::string Column::ToString() const {
    std::ostringstream os;

    os << "Column[" << column_name_ << ", " << column_type_ << ", "
       << "Offset:" << column_offset_ << ", ";

    if (IsInlined()) {
        os << "FixedLength:" << fixed_length_;
    } else {
        os << "VarLength:" << variable_length_;
    }
    os << "]";
    return (os.str());
}

std::string Column::Serialize() const {
    uint32_t column_name_size = column_name_.size();
    uint32_t column_type = column_type_;
    std::string res;
    res.resize(sizeof(column_type) + sizeof(column_offset_) + sizeof(column_name_size) + column_name_size);
    char *copy_ptr = const_cast<char *>(res.data());
    memcpy(copy_ptr, &column_type, sizeof(column_type));
    copy_ptr += sizeof(column_type);
    memcpy(copy_ptr, &column_offset_, sizeof(column_offset_));
    copy_ptr += sizeof(column_offset_);
    memcpy(copy_ptr, &column_name_size, sizeof(column_name_size));
    copy_ptr += sizeof(column_name_size);
    memcpy(copy_ptr, column_name_.data(), column_name_size);
    return res;
}

Column::Column(std::string serialized_data) {
    uint32_t column_name_size;
    uint32_t column_type;
    char *copy_ptr = const_cast<char *>(serialized_data.data());
    memcpy(&column_type, copy_ptr, sizeof(column_type));
    column_type_ = static_cast<TypeId>(column_type);
    copy_ptr += sizeof(column_type);
    memcpy(&column_offset_, copy_ptr, sizeof(column_offset_));
    copy_ptr += sizeof(column_offset_);
    memcpy(&column_name_size, copy_ptr, sizeof(column_name_size));
    copy_ptr += sizeof(column_name_size);
    column_name_.resize(column_name_size);
    memcpy((void *) column_name_.data(), copy_ptr, column_name_size);
    fixed_length_ = TypeSize(column_type_);
}

} // namespace benxdb